package com.aishua.andpaydemo.activity;

import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.nfc.tech.IsoDep;
import android.nfc.tech.NfcA;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.aishua.andpaydemo.ImageloaderHelper;
import com.aishua.andpaydemo.R;
import com.aishua.andpaydemo.utils.LogUtils;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by aishua on  2018/5/18.
 */

public class NfcTagActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "NfcTagActivity--";
    private ImageView img_title_xiaoxi;
    private ImageView img_xiaofeizonge;
    private ImageView hebaoyongquan;
    private ImageView hebaozhifu;
    private ImageView querenzhifu;
    private TextView tv_title;
    private TextView tv_setting;

    public String[][] TECHLISTS;
    public IntentFilter[] FILTERS;
    private NfcAdapter mNfcAdapter;
    private PendingIntent pendingIntent;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_nfctag);
        initView();

    }

    @Override
    protected void onResume() {
        super.onResume();

        initNFC();
        Intent intent = getIntent();
        readTag(intent);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void initView() {

        img_title_xiaoxi = findViewById(R.id.img_title_xiaoxi);
        tv_setting = findViewById(R.id.tv_setting);
        tv_title = findViewById(R.id.tv_title);

        img_title_xiaoxi.setBackground(getDrawable(R.drawable.back));
        img_title_xiaoxi.setOnClickListener(this);
        tv_title.setText("全聚德（菜市口店）");
        tv_setting.setVisibility(View.INVISIBLE);


        img_xiaofeizonge = findViewById(R.id.img_xiaofeizonge);
        hebaoyongquan = findViewById(R.id.hebaoyongquan);
        hebaozhifu = findViewById(R.id.hebaozhifu);
        querenzhifu = findViewById(R.id.querenzhifu);
        ImageloaderHelper.dispalyImage(this,R.drawable.xiaofeizonge,img_xiaofeizonge);
        ImageloaderHelper.dispalyImage(this,R.drawable.hebaoyongquan,hebaoyongquan);
        ImageloaderHelper.dispalyImage(this,R.drawable.hebaozhifu,hebaozhifu);
        ImageloaderHelper.dispalyImage(this,R.drawable.querenzhifu,querenzhifu);

    }


    private void initNFC() {
        LogUtils.v(TAG + "initNFC()");
        try {
            TECHLISTS = new String[][]{
                    {IsoDep.class.getName()},
                    {NfcA.class.getName()}
            };
            FILTERS = new IntentFilter[]{new IntentFilter(
                    NfcAdapter.ACTION_TECH_DISCOVERED, "*/*")};
        } catch (Exception e) {
            e.printStackTrace();
        }
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);


    }

    public void readTag(Intent intent) {
        LogUtils.v(TAG + "readTag()");
        LogUtils.v(TAG + "intent:" + intent.getAction());
        if ("android.nfc.action.NDEF_DISCOVERED".equals(intent.getAction()) || "android.nfc.action.TECH_DISCOVERED".equals(intent.getAction())) {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES");
            if (rawMsgs != null) {
                NdefMessage[] msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
                try {
                    JSONObject jsonObject = new JSONObject(new String(msgs[0].getRecords()[0].getPayload()));
                } catch (JSONException e) {
                    e.printStackTrace();
                    new AlertDialog.Builder(this).setTitle("提示").setMessage("该标签内没有信息，请先写入！")
                            .setPositiveButton("确认", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // TODO Auto-generated method stub
                                    dialog.dismiss();
                                }
                            }).setCancelable(false).show();
                }
            }
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.img_title_xiaoxi:

                gotoMainact();
                finish();
                break;
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
//            finish();
            gotoMainact();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    public void gotoMainact() {

        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }
}
